package com.example.ecommerceauthoritycenter.controller;


import com.alibaba.fastjson.JSON;
import com.example.ecommerceauthoritycenter.service.IJWTService;
import com.example.ecommercecommon.vo.JwtToken;
import com.example.ecommercecommon.vo.UserNameAndPassword;
import com.example.ecommercemvcconfig.annotation.IgnoreResponseAdvice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/authority")
public class AuthorityController {

    @Autowired
    private IJWTService ijwtService;


    /**
     * 从授权中心获取token（其实就是登录功能），且返回信息中没有统一响应的包装
     */
    @IgnoreResponseAdvice
    @PostMapping("/token")
    public JwtToken token(@RequestBody UserNameAndPassword userNameAndPassword) throws Exception {
        log.info("request to get token with param: [{}]",
                JSON.toJSONString(userNameAndPassword));

        JwtToken token = new JwtToken(
                ijwtService.generateToken(
                        userNameAndPassword.getUsername(),
                        userNameAndPassword.getPassword()
                )
        );
        return token;
    }


    @IgnoreResponseAdvice
    @PostMapping("/register")
    public JwtToken register(@RequestBody UserNameAndPassword userNameAndPassword) throws Exception {
        log.info("register user with param: [{}]", JSON.toJSONString(
                userNameAndPassword
        ));

        JwtToken token = new JwtToken(
                ijwtService.registerUserAndGenerateToken(
                        userNameAndPassword
                )
        );
        return token;
    }


}